import { XDomain } from '@/ts/base/schema';
import { Controller } from '.';
import { kernel } from '../base';
import { PlatformDomainBinding } from '../base/model';
import binding from '@/../config/domain';
import { IDisposable } from '../base/common';
import _ from 'lodash';
import Theme from '../core/thing/domain/theme';

// 在登录之前调用

export class DomainController extends Controller implements IDisposable {
  readonly domain: string;
  private domainSettingCollName = 'public-read-domain-setting';

  constructor(domain: string) {
    super('domain');
    this.domain = domain;
  }

  domainBinding: PlatformDomainBinding | undefined = binding;
  domainSetting: XDomain | undefined;
  private _theme: Theme = new Theme(undefined);

  get theme() {
    return this._theme;
  }

  async init(): Promise<XDomain | undefined> {
    if (!this.domainBinding) {
      return;
    }

    const ret2 = await kernel.collectionLoad<XDomain[]>(
      this.domainBinding.targetId,
      this.domainBinding.belongId,
      [],
      this.domainSettingCollName,
      {},
    );

    console.warn(ret2);

    const settings = ret2.data || [];
    let setting = settings.find((s) => s.isEnabled);
    if (!setting) {
      setting = settings[0];
    }
    this.domainSetting = setting;

    this._theme = new Theme(this.domainSetting);
    this._theme.init();

    return this.domainSetting;
  }

  async loadTheme() {
    this._theme!.loadCssVars();
  }

  dispose() {
    this._theme?.dispose();
  }
}

export default new DomainController(window.location.host);
